package com.restkeeper.store.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.store.entity.DishCategory;
import com.restkeeper.store.entity.Table;
import com.restkeeper.store.entity.TableArea;
import com.restkeeper.store.mapper.TableAreaMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@Service(version = "1.0.0",protocol = "dubbo")
public class TableAreaServiceImpl extends ServiceImpl<TableAreaMapper, TableArea> implements ITableAreaService{


    @Autowired
    ITableService tableService;

    @Override
    public IPage<TableArea> queryPage(long pageNo, long pageSize) {
        IPage<TableArea> page = new Page<>(pageNo,pageSize);
        QueryWrapper<TableArea> qw = new QueryWrapper<>();
        qw.lambda()
            .orderByDesc(TableArea::getLastUpdateTime);
        return this.page(page,qw);
    }


    public boolean add(TableArea area){
        checkNameExsis(area.getAreaName());
        return  this.save(area);
    }

    /**
     * 区域名称去重判断
     * @param name
     */
    private void checkNameExsis(String name){
        QueryWrapper<TableArea> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TableArea::getAreaId)
                .eq(TableArea::getAreaName,name);
        Integer count = this.count(qw);
        if(count > 0) throw new BussinessException("该区域已存在");
    }

    @Override
    public List<Map<String, Object>> listTableArea(){
        QueryWrapper<TableArea> qw = new QueryWrapper<>();
        qw.lambda().select(TableArea::getAreaId,TableArea::getAreaName).orderByDesc(TableArea::getIndexNumber);
        return this.listMaps(qw);
    }

    @Override
    public boolean deleteArea(String areaId) {
        QueryWrapper<Table> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(Table::getAreaId, areaId);
        if(tableService.count(qw)>0){
           throw new BussinessException("区域下有桌台信息，不能删除");
        }
        return this.removeById(areaId);
    }
}
